package com.example.module.api;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;

public class HttpMultipartTask extends AsyncHttpTask {
	private static final String TAG = "HttpMultipartTask";

	public HttpMultipartTask(Context context) {
		super(context);
	}

	@Override
	protected HttpTaskReponse doRequest(APIRequest request) throws Exception {
		HttpPost httpRequest = new HttpPost(request.getURL());
//		httpRequest.setHeader("SessionKey", mSessionKey);
		
		try {
			MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT);
			
			if (request.getParams() != null) {
				for (Entry<String, String> entry : request.getParams().entrySet()) {
					reqEntity.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.forName("UTF-8")));	
				}
			}
			
			if (request.getFiles() != null && request.getFiles().size() > 0) {
				for (Entry<String, File> entry : request.getFiles().entrySet()) {
					String name = entry.getKey();
					File file = entry.getValue();
					Log.d(TAG, "uploading name=" + name + " file=" + file.getAbsolutePath());
				
					reqEntity.addPart(name, new FileBody(file, "application/octet-stream"));
				}
			}
			
			httpRequest.setEntity(reqEntity);
			
			publishProgress((int) 10, (int) 20);
			
			HttpResponse response = client.execute(httpRequest);
			
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				publishProgress((int) 70, (int) 90);
				
				HttpEntity resEntity = response.getEntity();
				String responseText = EntityUtils.toString(resEntity, HTTP.UTF_8);
						
				Log.d(TAG, "responseText=" + responseText);
				
				return new HttpTaskReponse(RESPONSE_OK, responseText);
			}
			else
				return new HttpTaskReponse(RESPONSE_FAIL, "Response StatusLine: " + response.getStatusLine().toString());
			
			
		} catch (Exception e) {
			e.printStackTrace();
			return new HttpTaskReponse(RESPONSE_FAIL, e.toString());
		}
	}

}
